package cn.monkey.transport.netty;

import cn.monkey.transport.core.Exchange;
import cn.monkey.transport.core.ExchangeContext;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import reactor.core.publisher.Mono;

public class SimpleNettyExchange implements NettyExchange {
    private final String id;
    protected final NettyConnection connection;

    protected final Channel channel;
    protected final ExchangeContext exchangeContext;

    public SimpleNettyExchange(String id,
                               Channel channel) {
        this.id = id;
        this.channel = channel;
        this.connection = this.newConnection(channel);
        this.exchangeContext = new AttributeKeyContext(channel);
    }

    protected NettyConnection newConnection(Channel channel) {
        return new SimpleNettyConnection(channel);
    }

    @Override
    public String id() {
        return this.id;
    }

    @Override
    public ExchangeContext context() {
        return this.exchangeContext;
    }

    @Override
    public NettyInbound inbound() {
        return this.connection;
    }

    @Override
    public NettyOutbound outbound() {
        return this.connection;
    }

    @Override
    public Mono<Void> close() {
        return this.connection.close();
    }

    @Override
    public boolean isActive() {
        return this.channel.isActive();
    }

    @Override
    public NettyExchange bind() {
        this.channel.attr(AttributeKey.valueOf(Exchange.class, Exchange.KEY)).set(this);
        return this;
    }
}
